<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-card class="section-card" shadow="never">
        <template #header>接触限值</template>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="危害分类" prop="type">
              <el-select v-model="formData.type" placeholder="请选择危害分类">
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.HAZARD_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="中文名" prop="cnName">
              <el-input v-model="formData.cnName" placeholder="请输入中文名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="首字母" prop="letter">
              <el-input v-model="formData.letter" placeholder="请输入首字母" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="英文名称" prop="enName">
              <el-input v-model="formData.enName" placeholder="请输入英文名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="合并组别" prop="whgroup">
              <el-select v-model="formData.whgroup" placeholder="请选择合并组别">
                <el-option label="一组" value="一组" />
                <el-option label="二组" value="二组" />
                <el-option label="三组" value="三组" />
                <el-option label="四组" value="四组" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="仅识别" prop="onlyReco">
              <el-radio-group v-model="formData.onlyReco">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="CAS" prop="cas">
              <el-input v-model="formData.cas" placeholder="请输入cas" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="MAC" prop="mac">
              <el-input v-model="formData.mac" placeholder="请输入mac"  >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="PC_TWA" prop="pcTwa">
              <el-input v-model="formData.pcTwa" placeholder="请输入pc_twa"  >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="PC_STEL" prop="pcStel">
              <el-input v-model="formData.pcStel" placeholder="请输入pc_stel"  >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="总尘" prop="totalDust">
              <el-input v-model="formData.totalDust" placeholder="请输入总尘"  >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="呼尘" prop="expiratoryDust">
              <el-input v-model="formData.expiratoryDust" placeholder="请输入呼尘"  >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="note">
              <el-input v-model="formData.note" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="18">
            <el-form-item label="临界不良健康" prop="healthEffects">
              <el-input v-model="formData.healthEffects" placeholder="请输入临界不良健康效应" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="section-card" shadow="never">
        <template #header>检测方法</template>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="项目分组" prop="jcgroup">
              <el-select v-model="formData.jcgroup" clearable placeholder="请选择分组">
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.JCGROUP)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测标准" prop="testStandard">
              <el-input-tag
                v-model="formData.testStandard"
                :max-collapse-tags="3"
                placeholder="请输入检测依据，按回车确认"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="解析液" prop="resolutionSolution">
              <el-input v-model="formData.resolutionSolution" placeholder="请输入解析液" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="空气收集器" prop="airCollectors">
              <el-input-tag
                v-model="formData.airCollectors"
                :max-collapse-tags="3"
                placeholder="请输入空气收集器，按回车确认"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="测量设备" prop="measuringEquipment">
              <el-input-tag
                v-model="formData.measuringEquipment"
                :max-collapse-tags="3"
                placeholder="请输入测量设备，按回车确认"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保存期限" prop="storageLife">
              <el-input v-model="formData.storageLife" placeholder="请输入保存期限" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="短时间" prop="shortTime">
              <el-input v-model="formData.shortTime" placeholder="请输入短时间">
                <template #append>min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="短时间流量" prop="shortTimeFlow">
              <el-input v-model="formData.shortTimeFlow" placeholder="请输入短时间流量" >
                <template #append>L/min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="长时间" prop="longTime">
              <el-input v-model="formData.longTime" placeholder="请输入长时间" >
                <template #append>min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="长时间流量" prop="longTimeFlow">
              <el-input v-model="formData.longTimeFlow" placeholder="请输入长时间流量"  >
                <template #append>L/min</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="定量下限" prop="dlxx">
              <el-input v-model="formData.dlxx" placeholder="请输入定量下限" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
<!--      <el-card class="section-card no-gap-card" shadow="never">-->
<!--        <template #header>定量浓度</template>-->
<!--        <el-table :data="formData.volumeSettings" border size="small" style="width: 100%">-->
<!--          <el-table-column label="采样体积(L)" min-width="160">-->
<!--            <template #default="scope">-->
<!--              <el-input v-model="scope.row.volume" placeholder="请输入采样体积" />-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="最低定量浓度(mg/m³)" min-width="180">-->
<!--            <template #default="scope">-->
<!--              <el-input v-model="scope.row.minConcentration" placeholder="请输入最低定量浓度" />-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column align="center" label="操作" width="160">-->
<!--            <template #default="scope">-->
<!--              <el-button link type="primary" @click="addVolumeRowAfter(scope.$index)"-->
<!--                >新增</el-button-->
<!--              >-->
<!--              <el-divider direction="vertical" />-->
<!--              <el-button link type="danger" @click="removeVolumeRow(scope.$index)">删除</el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->
<!--      </el-card>-->
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { HazardsApi, HazardsVO } from '@/api/system/hazards'

/** 危害因素 表单 */
defineOptions({ name: 'HazardsForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 基于首个中文字符，粗略推断拼音首字母（A-Z），用于回显缺失首字母时的兜底
const getFirstPinyinLetter = (name?: string): string => {
  if (!name) return ''
  const match = name.match(/[\u4e00-\u9fa5]/)
  if (!match) return ''
  const ch = match[0]
  // 采用常见首字母分段法，非精准拼音库，但能覆盖大多数情况
  const letters = 'ABCDEFGHJKLMNOPQRSTWXYZ'
  const zh = '阿八嚓哒妸发旮哈讥咔垃妈拿哦啪七冉撒他哇昔压匝'
  for (let i = 0; i < letters.length; i++) {
    const start = zh[i]
    const end = zh[i + 1]
    if (!end) {
      if (ch.localeCompare(start) >= 0) return letters[i]
    } else if (ch.localeCompare(start) >= 0 && ch.localeCompare(end) < 0) {
      return letters[i]
    }
  }
  return ''
}

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  type: undefined,
  whgroup: undefined,
  jcgroup: undefined,
  onlyReco: 0,
  cnName: undefined,
  letter: undefined,
  enName: undefined,
  cas: undefined,
  mac: undefined,
  pcTwa: undefined,
  pcStel: undefined,
  totalDust: undefined,
  expiratoryDust: undefined,
  healthEffects: undefined,
  testStandard: undefined,
  airCollectors: [],
  storageLife: undefined,
  resolutionSolution: undefined,
  measuringEquipment: undefined,
  samplingMedium: undefined,
  shortTime: undefined,
  shortTimeFlow: undefined,
  longTime: undefined,
  longTimeFlow: undefined,
  dlxx: undefined,
  note: undefined,
  volumeSettings: []
})
const formRules = reactive({
  type: [{ required: true, message: '请选择危害分类', trigger: 'change' }],
  cnName: [{ required: true, message: '请输入中文名', trigger: 'blur' }],
  letter: [{ required: true, message: '请输入首字母', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await HazardsApi.getHazards(id)
      // 仅识别 onlyReco：后端可能返回 boolean 或字符串，统一转换为 0/1 以匹配单选
      if (typeof (data as any).onlyReco === 'boolean') {
        ;(data as any).onlyReco = (data as any).onlyReco ? 1 : 0
      } else if (typeof (data as any).onlyReco === 'string') {
        const v = (data as any).onlyReco.toLowerCase()
        ;(data as any).onlyReco = v === 'true' ? 1 : 0
      } else if ((data as any).onlyReco !== 1 && (data as any).onlyReco !== 0) {
        ;(data as any).onlyReco = 0
      }
      // 处理数组字段，将字符串转为数组
      if (data.airCollectors) {
        data.airCollectors = data.airCollectors.split(',')
      }
      if (data.testStandard) {
        data.testStandard = data.testStandard.split(',')
      }
      if (data.measuringEquipment) {
        data.measuringEquipment = data.measuringEquipment.split(',')
      }
      // 采样体积设置：后端以 JSON 字符串存储时，这里解析
      if (typeof data.volumeSettings === 'string') {
        try {
          data.volumeSettings = JSON.parse(data.volumeSettings)
        } catch (e) {
          data.volumeSettings = []
        }
      }
      if (!Array.isArray(data.volumeSettings)) {
        data.volumeSettings = []
      }
      if (data.volumeSettings.length === 0) {
        data.volumeSettings.push(createEmptyVolumeRow())
      }
      // 若首字母为空，尝试用中文名的首个中文字符推断拼音首字母
      if ((!data.letter || String(data.letter).trim() === '') && data.cnName) {
        const initial = getFirstPinyinLetter(String(data.cnName))
        if (initial) {
          data.letter = initial
        }
      }
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as HazardsVO
    // whgroup 未选择时，保存为 '—'
    if (data.whgroup === undefined || data.whgroup === null || data.whgroup === '') {
      ;(data as any).whgroup = '—'
    }
    // 仅识别 onlyReco：1/0 转换回 boolean 提交
    if ((data as any).onlyReco === 1) {
      ;(data as any).onlyReco = true
    } else if ((data as any).onlyReco === 0 || (data as any).onlyReco === undefined) {
      ;(data as any).onlyReco = false
    }
    // 处理数组字段，将数组转为字符串
    if (Array.isArray(data.airCollectors)) {
      data.airCollectors = data.airCollectors.join(',')
    }
    if (Array.isArray(data.testStandard)) {
      data.testStandard = data.testStandard.join(',')
    }
    if (Array.isArray(data.measuringEquipment)) {
      data.measuringEquipment = data.measuringEquipment.join(',')
    }
    // volumeSettings 为空项替换为 '—' 后再序列化
    if (Array.isArray((data as any).volumeSettings)) {
      const normalized = (data as any).volumeSettings.map((row: any) => {
        const volume = row?.volume
        const minConcentration = row?.minConcentration
        return {
          volume:
            volume === undefined || volume === null || (typeof volume === 'string' && volume.trim() === '')
              ? '—'
              : volume,
          minConcentration:
            minConcentration === undefined || minConcentration === null || (typeof minConcentration === 'string' && minConcentration.trim() === '')
              ? '—'
              : minConcentration
        }
      })
      ;(data as any).volumeSettings = JSON.stringify(normalized)
    }
    // 将未填写的可选字段统一保存为 '—'（保留必要字段与已序列化字段）
    const excludeKeys = new Set(['id', 'type', 'onlyReco', 'volumeSettings'])
    Object.keys(data as any).forEach((key) => {
      if (excludeKeys.has(key)) return
      const value = (data as any)[key]
      if (value === undefined || value === null || (typeof value === 'string' && value.trim() === '')) {
        ;(data as any)[key] = '—'
      }
    })
    console.log('提交的表单数据：', JSON.stringify(data))
    if (formType.value === 'create') {
      await HazardsApi.createHazards(data)
      message.success(t('common.createSuccess'))
    } else {
      await HazardsApi.updateHazards(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    type: undefined,
    whgroup: undefined,
    jcgroup: undefined,
    onlyReco: 0,
    cnName: undefined,
    letter: undefined,
    enName: undefined,
    cas: undefined,
    mac: undefined,
    pcTwa: undefined,
    pcStel: undefined,
    totalDust: undefined,
    expiratoryDust: undefined,
    healthEffects: undefined,
    testStandard: undefined,
    airCollectors: [],
    storageLife: undefined,
    resolutionSolution: undefined,
    measuringEquipment: undefined,
    samplingMedium: undefined,
    shortTime: undefined,
    shortTimeFlow: undefined,
    longTime: undefined,
    longTimeFlow: undefined,
    dlxx: undefined,
    note: undefined,
    volumeSettings: [createEmptyVolumeRow()]
  }
  formRef.value?.resetFields()
}

// 采样体积设置 - 行操作
const createEmptyVolumeRow = () => ({ volume: '', minConcentration: '' })

const addVolumeRowAfter = (index: number) => {
  if (!Array.isArray(formData.value.volumeSettings)) {
    formData.value.volumeSettings = []
  }
  formData.value.volumeSettings.splice(index + 1, 0, createEmptyVolumeRow())
}
const removeVolumeRow = (index: number) => {
  formData.value.volumeSettings.splice(index, 1)
  if (formData.value.volumeSettings.length === 0) {
    formData.value.volumeSettings.push(createEmptyVolumeRow())
  }
}
</script>
<style scoped>
.section-card {
  margin-bottom: 12px;
}

.section-card :deep(.el-card__header) {
  font-weight: 600;
  padding: 10px 16px;
}

.section-card :deep(.el-card__body) {
  padding-top: 10px;
  padding-bottom: 4px;
}

.no-gap-card :deep(.el-card__body) {
  padding: 0;
}
</style>
